package io.github.talelin.latticy.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.github.talelin.autoconfigure.exception.NotFoundException;
import io.github.talelin.latticy.dto.DocumentDTO;
import io.github.talelin.latticy.entity.Document;
import io.github.talelin.latticy.mapper.DocumentMapper;
import io.github.talelin.latticy.model.DocumentDO;
import io.github.talelin.latticy.repository.DocumentRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class DocumentService extends ServiceImpl<DocumentMapper, DocumentDO> {
    @Autowired
    private DocumentRepository documentRepository;

    public Document get(Long id) {
        Optional<Document> document = documentRepository.findById(id);
        return document.orElseThrow(() -> new NotFoundException());
    }

    public Page<Document> getALl(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return documentRepository.findByOrderBySortDesc(pageable);
    }


    /********************* 后台 *******************************/
    public void create(DocumentDTO dto) {
        DocumentDO documentDO = new DocumentDO();
        BeanUtils.copyProperties(dto, documentDO);
        this.save(documentDO);
    }

    public void updated(Long id, DocumentDTO dto) {
        DocumentDO documentDO = this.getById(id);
        BeanUtils.copyProperties(dto, documentDO);
        this.updateById(documentDO);
    }

    public void delete(Long id) {
        DocumentDO documentDO = this.getById(id);
        this.getBaseMapper().deleteById(id);
    }

    public DocumentDO getDocument(Long id) {
        DocumentDO documentDO = this.getById(id);
        if (documentDO == null) {
            throw new NotFoundException();
        }
        return documentDO;
    }


}
